/*
 * Copyright 2025 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.sychip.fhc.app.wsn.screen

import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.viewModelScope
import com.fhc.base.EventBusSubGInfo
import com.fhc.usb.UsbDeviceDto
import com.fhc.usb.UsbSerialManager
import com.sychip.fhc.MainApplication
import com.sychip.fhc.app.pref.AppSetting
import com.sychip.fhc.app.pref.PrefDataStoreIf
import com.sychip.fhc.app.wsn.nav.WsnUsbStatus
import com.sychip.fhc.base.BaseAppViewModel
import com.sychip.fhc.di.ApplicationScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted.Companion.Eagerly
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class WsnAboutViewModel @Inject constructor(
    app: MainApplication,
    private val prefDataStore: PrefDataStoreIf,
    @ApplicationScope private val appScope: CoroutineScope,
) : BaseAppViewModel(app, prefDataStore) {
    private val _usbFlow = MutableStateFlow(WsnUsbStatus())
//    val usbFlow: StateFlow<WsnUsbStatus> = _usbFlow.asStateFlow()


    private val _appSettingFlow = MutableStateFlow<AppSetting>(AppSetting())
    val appSettingFlow: StateFlow<AppSetting> = _appSettingFlow.asStateFlow()
    private fun observeAppSetting() {
        prefDataStore.getAppSettings().map { result ->
            _appSettingFlow.update {result}
        }.launchIn(viewModelScope)
    }
    fun toggleMockMode() {
        viewModelScope.launch {
            val appSetting = _appSettingFlow.value.copy(mockMode = !_appSettingFlow.value.mockMode)
            prefDataStore.saveAppSettings(appSetting)
        }
    }
    init {
        observeUsbDevice()
        observeAppSetting()
        startPeriodicSync()
    }

    private val _subG = MutableStateFlow(EventBusSubGInfo())
    val subG: StateFlow<EventBusSubGInfo> = _subG.asStateFlow()


    // 使用StateFlow包装DataStore数据流
    private val _usbDevice = MutableStateFlow<UsbDeviceDto?>(null)
    val usbDevice: StateFlow<UsbDeviceDto?> = _usbDevice.asStateFlow()

    // 使用StateFlow包装DataStore数据流
    private val _usbOnline = MutableStateFlow(false)
    val usbOnline: StateFlow<Boolean> = _usbOnline.asStateFlow()

    private fun observeUsbDevice() {
        prefDataStore.getUsbDevice().map {result ->
            _usbFlow.update { WsnUsbStatus(isNew = false, usb = result)  }

//            Timber.e("serialNumber:%s", result?.serialNumber)
            _usbDevice.value = result
            _usbOnline.update { UsbSerialManager.instance()?.getActiveDevice() != null }

        }.stateIn(
            scope = viewModelScope,
            started = Eagerly,
            initialValue = mutableStateOf<UsbDeviceDto?>(null)
        )
    }

fun getSubgInfo() {
    if (_usbOnline.value) {
        UsbSerialManager.instance()?.write("XKNGETINFO")
    }
}

    fun startPeriodicSync() {
        appScope.launch {
            while (isActive) {
//                fetchNotifications() // 每10分钟同步一次
                delay(3 * 1000L)
            }
        }
    }
//    fun saveSubGInfo(subG: EventBusSubGInfo) {
//        appScope.launch {
//            val cmdSetInfo = "XKNSETINFO " + subG.channel + ' ' + subG.port + ' ' + subG.panId + "\r\n"
//            Timber.i("saveSubGInfo  :%s", cmdSetInfo)
//            if (_usbOnline.value) {
//                UsbSerialManager.instance()?.write(cmdSetInfo)
//                delay(100L)
//                val cmdXknGw = "XKNGW 7FFF" + "\r\n"
//                UsbSerialManager.instance()?.write(cmdXknGw)
//                delay(100L)
//                val cmdSetKey = "XKSETKEY " + subG.key + "\r\n"
//                UsbSerialManager.instance()?.write(cmdSetKey)
//                delay(100L)
//                UsbSerialManager.instance()?.write(cmdXknGw)
//                delay(100L)
//            }
//        }
//    }
//
//    private val _licenseShowState = MutableStateFlow(false)
//    val licenseShowState: StateFlow<Boolean> = _licenseShowState.asStateFlow()
//
//    fun showLicense(show: Boolean) =  viewModelScope.launch {
//        _licenseShowState.update {
//            show
//        }
//    }
}
